#include <iostream>
#include <string>

#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>

#include <cstring>    
#include <cstdlib>
using namespace std;

void Usage(const string proc)
{
    cout << "Usage:\n\t" << proc << " serverip serverport\n"<<endl;
}

//./tcpclient serverip serverport
int main(int argc,char* argv[])
{
    if(argc!=3)
    {
        Usage(argv[0]);
        exit(1);
    }
    string serverip=argv[1];
    uint16_t serverport=stoi(argv[2]);

    //1. 创建socket套接字
    int sockfd=socket(AF_INET,SOCK_STREAM,0);
    if(sockfd<0)
    {
        cerr<<"socket error"<<endl;
        exit(2);
    }
    //2.构建目标主机信息&&将网络信息与主机信息首次调用connect时由操作系统进行绑定
    struct sockaddr_in server;
    memset(&server,0,sizeof(server));
    server.sin_family=AF_INET;
    server.sin_port=htons(serverport);
    server.sin_addr.s_addr=inet_addr(serverip.c_str());

    //3.客户端发送连接请求
    //connect返回值为0说明绑定与发起连接成功
    int n=connect(sockfd,(struct sockaddr*)&server,sizeof(server));
    if(n<0)
    {
        cout<<"connect error"<<endl;
        exit(3);
    }

    while(true)
    {
        cout<<"Please Enter# ";
        string message;
        getline(cin,message);
        ssize_t s=send(sockfd,message.c_str(),message.size(),0);
        if(s>0)
        {
            //发送成功后接收服务端返回的消息
            char buffer[1024];
            ssize_t m=recv(sockfd,buffer,sizeof(buffer)-1,0);
            if(m>0)
            {
                buffer[m]=0;
                cout<<buffer<<endl;
            }
            else
            {
                break;
            }
        }
        else
        {
            break;
        }
    }
    ::close(sockfd);
    return 0;
}